from pyparsing import *
import string

import Scope
import BoxAssignmentParser
import SubProgramParser
import VarAssignmentParser
import DebugParser

SHOULD_DEBUG_PRINT = False

BoxAssignment = BoxAssignmentParser.BoxAssignment
SubProgram = SubProgramParser.SubProgram
VarAssignment = VarAssignmentParser.VarAssignment
DebugLine = DebugParser.DebugLine

def varAssignmentParseAction(s, loc, toks):
    varname = toks[0]
    varvalue = toks[1]
    Scope.add_var(varname,varvalue)
    if SHOULD_DEBUG_PRINT:
        print 'PARSED VAR:',varname,varvalue
    return toks

def subProgramParseAction(s,loc,toks):
    sp = toks[0]
    fname = sp.name
    Scope.add_func(fname,sp)
    if SHOULD_DEBUG_PRINT:
        print 'PARSED SUB:',fname,sp
    return toks

def boxParseAction(s,loc,toks):
    boxname = toks[0]
    box_instance = toks[1]
    Scope.add_box(boxname, box_instance)
    if SHOULD_DEBUG_PRINT:
        print 'PARSED BOX:',boxname,box_instance
    return toks
    
BoxAssignment.addParseAction( boxParseAction )
SubProgram.addParseAction( subProgramParseAction )
VarAssignment.addParseAction(varAssignmentParseAction)
# These will add the parsed boxes/vars/programs to the scope


MeaningfulLine = BoxAssignment | SubProgram |VarAssignment| DebugLine
DSLProgram = ZeroOrMore(MeaningfulLine)

def parseFile(filename):
    try:
        results = DSLProgram.parseFile(filename)
        return Scope.getScope()
    except ParseException, pe:
        print pe

def parseString(stringToParse):
    try:
        results = DSLProgram.parseString(stringToParse)
        return Scope.getScope()
    except ParseException, pe:
        print pe

def parse(filename):
    return parseFile(filename)

shorttest = """
mr_box <- (button:40x40)[text="hey"]
other_box <-(button:?x?)[text="lala"]

main_window <-  other_box

"""

shortertest ="""
other_box <-(button:?x?)[text="lala"]

main_window <-  other_box

"""

if __name__=='__main__':
    test = shortertest
    
    header = 'Parser Tester begins:\n'
    print header + '=' * (len(header)-1)
    print test
    print '-' * (len(header)-1) + '\n'
    try:
        results = DSLProgram.parseString(test)
        print '-' * (len(header)-1)
        print results
        print Scope.get_box("main_window").children
    except ParseException, pe:
        print "Parsing failed:"
        print test
        print "%s^" % (' '*(pe.col-1))
        print pe    
